<?php
namespace app\api\controller;

// 1. 资源及配置加载

require_once  dirname(__FILE__). "/../../../extend/AdapaySdkOld/init.php";
use think\Request;
use think\Db;
use app\api\model\OrderCommon;
use app\api\model\Topup;
use app\service\RechargeWithdrawMatcher;

class AdapayOld extends Common
{
    //旧的
    public $APP_ID = "app_ff810e42-ab89-44b0-9019-000db5382fa5";
    public $ADAPAY_MERCHANTID = "0716040022539392";

    public $WECHAT_MINI_APPID = "wx5143d1de2faf020b";
    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        \AdaPayOld\AdaPay::init(dirname(__FILE__). "/../../../extend/AdapayCoreOld.json", "live", false);
    }

    public function index($order_sn = '', $total_amount = '0.02', $trade_type = 'alipay', $goods_title = '账户充值')
    {
        // alipay 支付宝 App 支付
        // alipay_qr 支付宝正扫
        // alipay_wap 支付宝 H5 支付
        // wx_pub 微信公众号支付
        // wx_lite 微信小程序支付
        // wx_scan 微信反扫

        # 初始化支付类


        $payment = new \AdaPaySdkOld\Payment();

        $total_amount = number_format($total_amount, 2, '.', '');

        $timenow = time();

        # 支付设置
        $payment_params = array(
            "app_id"=> $this->APP_ID,
            "order_no"=> uniqid('cz'),
            "pay_channel"=> 'wx_lite',
            "time_expire"=> date('YmdHis', $timenow + 60 * 15),
            "pay_amt"=> $total_amount,
            "goods_title"=> $goods_title,
            "goods_desc"=> $goods_title,
            "pay_mode"=>"delay",
            "description"=> $order_sn,
            "notify_url"=> url('api/AdapayOld/notify', '', '', true),
        );


        // $rechargeTypes = ['账户充值'=>1, '会员充值'=>2];
        // $rechargeType = $rechargeTypes[$goods_title]??1;
        // $matchs = RechargeWithdrawMatcher::matchWithdrawOrdersFIFO($payment_params['order_no'], $total_amount, $rechargeType);
        // halt($matchs);
        // $payment_params['div_members'] = [
        //     ['member_id'=>0, 'amount'=>'0.50', 'fee_flag'=>'Y'],
        //     ['member_id'=>1, 'amount'=>'0.50', 'fee_flag'=>'N'],
        // ];

        # 发起支付
        $payment->create($payment_params);

        # 对支付结果进行处理
        if ($payment->isError()){
            //失败处理
            return $this->miss($payment->result);
        } else {

            //   \think\Log::write($payment->result, 'error');
            $payment->result['data'] = $payment->result['expend'];
            $payment->result['data']['qr_code'] = $payment->result['expend']['pay_info'];

            //成功处理
            return $this->pass($payment->result);
        }
    }

    public function mini($order_sn = '', $goods_desc = '账户充值', $open_id = 'oEz9a7IqdyYIa2HXAoQfBcS_Bcv4')
    {

        $result = $this->check($order_sn);
        if ($result['code'] != 200) {
            return $this->miss($result['msg']);
        }

        $total_amount = $result['data']['total_amount'];

        # 初始化支付类
        $payment = new \AdaPaySdkOld\Payment();

        $timenow = time();

        # 支付设置
        $payment_params = array(
            "app_id"=> $this->APP_ID,
            "order_no"=> uniqid('cz'),
            "pay_channel"=> "wx_lite",
            "time_expire"=> date('YmdHis', $timenow + 60 * 15),
            "pay_amt"=> $total_amount,
            "goods_title"=> $goods_desc,
            "goods_desc"=> $goods_desc,
            "description"=> $order_sn,
            "notify_url"=> url('api/AdapayOld/notify', '', '', true),
            "pay_mode"=>"delay",
            "expend"=>[
                'open_id'=>$open_id,
                "wx_app_id"=>$this->WECHAT_MINI_APPID
            ]
        );

        # 发起支付
        $payment->create($payment_params);

        # 对支付结果进行处理
        if ($payment->isError()){

            //失败处理
            return $this->miss($payment->result);
        } else {

            //成功处理
            return $this->pass($payment->result);
        }
    }

    public function notify()
    {
        $adapay_tools = new \AdaPaySdkOld\AdapayTools();


        $post_data = json_decode($_POST['data'],1);
        $post_data_str = json_encode($post_data,JSON_UNESCAPED_UNICODE);
        $post_sign_str = isset($_POST['sign']) ? $_POST['sign']: '';


        // $post_data_str = "{\"app_id\":\"app_55dcbd98-988e-45d4-aafd-93e0833f2e64\",\"created_time\":\"20210827154320\",\"description\":\"description\",\"end_time\":\"20210827154414\",\"expend\":{\"sub_open_id\":\"2088002620020732\"},\"fee_amt\":\"0.01\",\"id\":\"002112021082715432010277234787138306048\",\"order_no\":\"C2021112799100519\",\"out_trans_id\":\"2021082722001420731428147993\",\"party_order_id\":\"02212108275660018000697\",\"pay_amt\":\"1.00\",\"pay_channel\":\"alipay\",\"status\":\"succeeded\"}";

        // $post_sign_str = "JDRZDnB+oKorcWjEsvvzDX3HI7dCfnxQ+/l780oFTG9MO6gGmCR6MiovfXLgpmlYyoCuHVjD/5cAVfJWppr+tgg3rzQFR+3O42ZXZxctTVJXp2fVszuYeSzipKFE60Jo3aavhgkt/5Hres77u353UXMkRxUHG/hMTIwPoxg789A=";

        $post_data = json_decode($post_data_str, true);

        # 先校验签名和返回的数据的签名的数据是否一致
        $sign_flag = $adapay_tools->verifySign($post_data_str, $post_sign_str);

        $order_sn = $post_data['description'];
        $order_info = $post_data;

        if ($sign_flag){
            // var_dump("签名验证通过");
            # 业务方自己的逻辑
            if ($order_info['status'] == 'succeeded') {
                $result = OrderCommon::notify($order_sn, $order_info);
            }
        }else{
            // var_dump("签名验证失败");
            # 业务方自己的逻辑
        }
    }

    public function refund($payment_id = '002212025041616573110758504544519999488', $refund_order_no = 'cz67ff70f8a6da4', $refund_amt = '4.84')
    {
        # 初始化退款对象
        $refund = new \AdaPaySdkOld\Refund();

        $refund_params = array(
            'id'=>'0022120250416170028990758505287465873408',
            # 原交易支付对象ID
            'payment_id'=> $payment_id,
            # 退款订单号
            'refund_order_no'=> $refund_order_no,
            # 退款金额
            'refund_amt'=> $refund_amt,
            # 退款描述
            'reason'=> '退款',
            # 扩展域
            'expend'=> '',
            # 设备静态信息
            'device_info'=> '',
            'fail_fast'=>'Y',
            'div_members'=>[
                ['member_id'=>11,'amount'=>'4.42'],
                ['member_id'=>0,'amount'=>'0.42']
            ]
        );

        # 发起退款
        $refund->create($refund_params);

        # 对退款结果进行处理
        # $refund->result 类型为数组
        if ($refund->isError()){
            //失败处理
            return $this->miss($refund->result['error_msg']);
        } else {
            //成功处理
            return $this->pass($refund->result);
        }

    }

    public function pay_confirm($payment_id = '002212025040117472710753081292897275904', $order_no = '', $confirm_amt = '0.01', $div_members = [])
    {
        # 初始化支付确认对象类
        $payment = new \AdaPaySdkOld\PaymentConfirm();

        $confirm_amt = number_format($confirm_amt, 2, '.', '');
        # 支付设置
        $payment_params = array(
            'payment_id'=> $payment_id,
            'order_no'=> $order_no ?: date("YmdHis").rand(100000, 999999),
            'confirm_amt'=> $confirm_amt,
            'description'=> '',
            'fee_mode'=>'O',
            'div_members'=> $div_members
        );
        // halt($payment_params);

        # 创建支付确认对象
        $payment->create($payment_params);

        # 对支付结果进行处理
        if ($payment->isError()){
            //失败处理
            return $this->miss($payment->result['error_msg']);
        } else {
            //成功处理
            return $this->pass($payment->result);
        }
    }

    public function query_pay_confirm_list()
    {
        # 初始化支付确认对象类
        $payment = new \AdaPaySdkOld\PaymentConfirm();

        # 参数
        $payment_params = array(
            "app_id"=> $this->APP_ID,
            "created_gte"=>"1571466657929"
        );

        # 查询支付确认对象列表
        $payment->queryList($payment_params);

        # 对支付结果进行处理
        if ($payment->isError()){
            //失败处理
            return $this->miss($payment->result['error_msg']);
        } else {
            //成功处理
            return $this->pass($payment->result);
        }
    }

    // 支付确认撤销【调用失败】
    public function payment_confirm_reverse($payment_confirm_id = '0022120250416170028990758505287465873408', $order_no = 'cz67ff70f8a6da4')
    {
        # 初始化支付确认对象类
        $payment = new \AdaPaySdkOld\AdaPayCommon();

        # 参数
        $payment_params = array(
            "adapay_func_code"=>"payments.confirm.reverse",
            "payment_confirm_id"=>$payment_confirm_id,
            "order_no"=>$order_no . time(),
        );

        # 查询支付确认对象列表
        $payment->requestAdapay($payment_params);

        # 对支付结果进行处理
        if ($payment->isError()){
            var_dump($payment->result);
            //失败处理
            return $this->miss($payment->result['error_msg']);
        } else {
            //成功处理
            return $this->pass($payment->result);
        }
    }

    // 创建用户
    public function create_user($member_id = 11)
    {
        # 初始化用户对象类
        $member = new \AdaPaySdkOld\Member();
        $member_params = array(
            # app_id
            'app_id'=> $this->APP_ID,
            # 用户id
            'member_id'=> $member_id,
            //    # 用户地址
            //    'location'=> '上海市闵行区汇付',
            //    # 用户邮箱
            //    'email'=> '123123@126.com',
            //    # 性别
            //    'gender'=> 'MALE',
            //    # 用户手机号
            //    'tel_no'=> '18177722312',
            //    # 用户昵称
            //    'nickname'=> 'test',
        );
        # 创建
        $member->create($member_params);

        # 对创建用户对象结果进行处理
        if ($member->isError()){
            //失败处理
            return $this->miss($member->result['error_msg']);
        } else {
            //成功处理
            return $this->pass($member->result);
        }
    }

    // 查询并创建用户
    public function query_user($member_id = 1)
    {
        # 初始化用户对象类
        $member = new \AdaPaySdkOld\Member();

        # 查询用户对象
        $member->query(['app_id'=> $this->APP_ID, 'member_id'=> $member_id]);

        # 对查询用户对象结果进行处理
        if ($member->isError()){
            return $createUser = $this->create_user($member_id);
            //失败处理
            return $this->miss($member->result['error_msg']);
        } else {
            //成功处理
            return $this->pass($member->result);
        }
    }

    // 查询结算账户
    public function query_settle_account($member_id = 0, $settle_account_id = '0721302959391040')
    {
        # 初始化结算账户对象类
        $account = new \AdaPaySdkOld\SettleAccount();

        $account_params = array(
            'app_id'=> $this->APP_ID,
            'member_id'=> $member_id,
            'settle_account_id'=> $settle_account_id
        );

        # 查询结算账户
        $account->query($account_params);

        # 对查询结算账户结果进行处理
        if ($account->isError()){
            //失败处理
            return $this->miss($account->result['error_msg']);
        } else {
            //成功处理
            return $this->pass($account->result);
        }
    }

    // 创建结算账户
    public function set_settle_account($member_id = 0, $account_info = [])
    {
        # 初始化结算账户对象类
        $account = new \AdaPaySdkOld\SettleAccount();

        $account_params = array(
            'app_id'=> $this->APP_ID,
            'member_id'=> $member_id,
            'channel'=> 'bank_account',
            'account_info'=> [
                'card_id' => '6214850430073202',
                'card_name' => '钟文聪',
                'cert_id' => '441322199903203334',
                'cert_type' => '00',
                'tel_no' => '18003094207',
                'bank_acct_type' => 2,
            ]
        );

        $account_params['account_info'] = $account_info;

        # 创建结算账户
        $account->create($account_params);

        # 对创建结算账户结果进行处理
        if ($account->isError()){
            //失败处理
            return $this->miss($account->result['error_msg']);
        } else {
            //成功处理
            return $this->pass($account->result);
        }
    }

    // 删除结算账户
    public function delete_settle_account($member_id = 0, $settle_account_id = '0721303015739392')
    {
        # 初始化结算账户对象类
        $account = new \AdaPaySdkOld\SettleAccount();

        $account_params = array(
            'app_id'=> $this->APP_ID,
            'member_id'=> $member_id,
            'settle_account_id'=> $settle_account_id
        );

        # 查询结算账户
        $account->delete($account_params);

        # 对查询结算账户结果进行处理
        if ($account->isError()){
            //失败处理
            return $this->miss($account->result['error_msg']);
        } else {
            //成功处理
            return $this->pass($account->result);
        }
    }

    // 用户余额
    public function query_user_balance($member_id=1, $settle_account_id = '0721303015739392')
    {
        # 初始化结算账户对象类
        $account = new \AdaPaySdkOld\SettleAccount();


        $account_params = array(
            'app_id'=> $this->APP_ID,
            'member_id'=> $member_id,
            'settle_account_id'=> $settle_account_id
        );

        # 查询账户余额
        $account->balance($account_params);


        # 对查询账户余额结果进行处理
        if ($account->isError()){
            //失败处理
            return $this->miss($account->result['error_msg']);
        } else {
            //成功处理
            return $this->pass($account->result);
        }
    }

    // 查询可用额度
    public function settle_accounts_balance_pay($cust_id = '0721303015739392')
    {
        # 初始化支付确认对象类
        $payment = new \AdaPaySdkOld\AdaPayCommon();

        # 参数
        $payment_params = array(
            "adapay_func_code"=>"settle_accounts.balancePa",
            "app_id"=>$this->APP_ID,
            "order_no"=>uniqid(),
            "out_member_id"=>0,
            "in_member_id"=>1,
            "trans_amt"=>0.01,
            "goods_title"=>'测试',
            "goods_desc"=>'测试',
        );

        # 查询支付确认对象列表
        $payment->requestAdapay($payment_params);

        # 对支付结果进行处理
        if ($payment->isError()){
            var_dump($payment->result);
            //失败处理
            return $this->miss($payment->result['error_msg']);
        } else {
            //成功处理
            return $this->pass($payment->result);
        }
    }

    // 取现
    public function drawcash($member_id = 0, $cash_amt = 0.01, $order_no = '')
    {
        # 初始化取现对象
        $drawcash = new \AdaPaySdkOld\Drawcash();

        $cash_amt = number_format($cash_amt, 2, '.', '');

        $drawcash_params = array(
            'order_no'=> $order_no?:"CS_". date("YmdHis").rand(100000, 999999),
            'app_id'=> $this->APP_ID,
            //'cash_type'=> $member_id?'D0':'D1',
            'cash_type'=> 'D0',
            'cash_amt'=> $cash_amt,
            'member_id'=> $member_id,
            "notify_url"=> url('api/AdapayOld/drawcash_notify', '', '', true),
            "fee_mode"=> 'O',//O:商户承担手续费，I:用户承担手续费
        );

        # 账户取现
        $drawcash->create($drawcash_params);

        # 对账户取现结果进行处理
        if ($drawcash->isError()){
            // echo "<pre>";
            // var_dump($drawcash->result);exit;
            //失败处理
            return $this->miss($drawcash->result['error_msg']);
        } else {
            //成功处理
            return $this->pass($drawcash->result);
        }
    }

    public function query_drawcash($order_no = 'CS_20250402111858609352')
    {
        # 初始化取现对象
        $drawcash = new \AdaPaySdkOld\Drawcash();


        $drawcash_params = array(
            'order_no'=> $order_no,
        );

        # 账户取现
        $drawcash->query($drawcash_params);

        # 对账户取现结果进行处理
        if ($drawcash->isError()){
            //失败处理
            return $this->miss($drawcash->result['error_msg']);
        } else {
            //成功处理
            return $this->pass($drawcash->result);
        }
    }

    public function drawcash_notify()
    {
        $adapay_tools = new \AdaPaySdkOld\AdapayTools();

        $post_data = json_decode($_POST['data'],1);
        $post_data_str = json_encode($post_data,JSON_UNESCAPED_UNICODE);
        $post_sign_str = isset($_POST['sign']) ? $_POST['sign']: '';

        $post_data = json_decode($post_data_str, true);

        # 先校验签名和返回的数据的签名的数据是否一致
        $sign_flag = $adapay_tools->verifySign($post_data_str, $post_sign_str);

        $order_sn = $post_data['order_no'];
        $order_info = $post_data;

        if ($sign_flag){

            $failed = $post_data['status'] == 'failed';
            if ($failed) {
                \think\Log::write($order_sn . '取现失败' . $post_data['error_msg'], 'error');
            } else {

            }
        }else{
        }
    }


    private function check($out_trade_no)
    {
        $state = 0;

        $data = (new Topup)->master()->where(['numbers' => $out_trade_no, 'state' => 0])->find();

        if ($data) {
            $state = 1;
            $money = $data['price'];
        }

        if (!$state) {
            $data = (new OrderCommon)->master()->where(['number' => $out_trade_no, 'status' => 0])->find();

            if ($data) {
                $state = 1;
                $money = $data['money'];
            }
        }

        if (!$state) {
            $data = Db::name('mall_order')->master()->where(['number' => $out_trade_no, 'status' => 0])->find();

            if ($data) {
                $state = 1;
                $money = $data['money'];
            }
        }

        if (!$state) {
            $data = Db::name('order_of_service')->master()->where(['number' => $out_trade_no, 'paystate' => 0, 'state' => 0])->find();

            if ($data) {
                $state = 1;
                $money = $data['price'];
            }
        }

        if (!$state) {
            $data = Db::name('user_flag')->master()->where(['number' => $out_trade_no, 'paystate' => 0, 'status' => 0])->find();

            if ($data) {
                $state = 1;
                $money = $data['price'];
            }
        }

        if (!$state) {
            $data = Db::name('user_address_red_packet')->master()->where(['number' => $out_trade_no, 'type' => 1, 'paystate' => 0])->find();

            if ($data) {
                $state = 1;
                $money = $data['totalprice'];
            }
        }

        if (!$state) {
            $data = Db::name('order_of_addressgood')->master()->where(['number' => $out_trade_no, 'status' => 0, 'paystate' => 0])->find();

            if ($data) {
                $state = 1;
                $money = $data['price'];
            }
        }

        if (!$state) {
            $data = Db::name('activity_join')->master()->where(['number' => $out_trade_no, 'paystate' => 0])->find();

            if ($data) {
                $state = 1;
                $money = $data['price'];
            }
        }

        if (!$state) {
            return ['code' => 400, 'msg' => '订单不存在'];
        } else {
            return ['code' => 200, 'data' => ['total_amount' => $money]];
        }
    }
}